package com.jtcoding.chat.service.impl;

import com.jtcoding.chat.dao.chat.ChatDao;
import com.jtcoding.chat.model.ChatDetail;
import com.jtcoding.chat.model.ChatRecord;
import com.jtcoding.chat.model.User;
import com.jtcoding.chat.service.ChatService;
import com.jtcoding.chat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Author jason.tang
 * @Date 2019/02/6 14:49
 * @Desc 聊天
 */
@Service("chatService")
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatDao chatDao;

    @Autowired
    private UserService userService;

    @Override
    public int addChatRecord(ChatRecord chatRecord) {
        return chatDao.addChatRecord(chatRecord);
    }

    @Override
    public List<ChatDetail> getChatListByNum(Integer userNum) {
        List<ChatDetail> chatDetails = new ArrayList<>();

        List<Integer> friendNums = chatDao.getChatListByNum(userNum);
        for (Integer friendNum : friendNums) {
            ChatDetail chatDetail = new ChatDetail();
            ChatRecord chatRecord;
            User user = userService.getUserByNum(friendNum);
            List<ChatRecord> unreadChatRecords = chatDao.getUnreadChatRecord(userNum, friendNum);
            if (!unreadChatRecords.isEmpty()) {
                unreadChatRecords.sort(Comparator.comparing(ChatRecord::getRecNum));
                chatRecord = unreadChatRecords.get(unreadChatRecords.size() - 1);
            } else {
                chatRecord = chatDao.getReadChatRecord(userNum, friendNum);
            }

            chatDetail.setDateTime(chatRecord.getCreateTime());
            chatDetail.setFriendNum(friendNum);
            chatDetail.setFriendName(user.getUsername());
            if (chatRecord.getMsgType().equals("text")) {
                chatDetail.setLastMsg(chatRecord.getMessage());
            } else {
                chatDetail.setLastMsg("[图片]");
            }
            chatDetail.setUnreadCount(unreadChatRecords.size());
            chatDetails.add(chatDetail);
        }
        return chatDetails;
    }
}
